from audio_pkg.core.argument.argument_parse import ArgumentParser
from audio_pkg.core.services.task_manager import TaskQuery,TaskCreator,TaskParser,TaskFilterSaver,TaskAutoSave
from audio_pkg.utils.get_token import GetAccessToken
from audio_pkg.core.services.audiosave import AudioSaver
from audio_pkg.utils.logger import setup_logger
from audio_pkg.models.configdata import AppConfig
from typing import List

# 7. 主处理器
class MainProcess:
    def __init__(self, config:AppConfig):
        self.logger = setup_logger()
        self.config = config
        
        self.args = ArgumentParser(self.config.voice).parse()
        self.token_manager = GetAccessToken(self.config.api)

        self.command_handlers = {
            "create": self.handler_create_task,
            "query": self.handler_query_task,
            "save": self.handler_save_task,
            "auto": self.auto_save
        }
        
        self.task_id = None
        self.task_data_list: List = None
        self.query_task = TaskQuery(self.config.urls.QUERY_TASK_URL,self.token_manager,self.logger)
        
    def handler_create_task(self):
        """创建任务并保存任务 ID 和格式"""
        task_creator = TaskCreator(
            self.config.resource.DEFAULT_TASK_JSON,
            self.config.urls.CREATE_TASK_URL,
            self.args, 
            self.logger,
            self.token_manager
        )
        self.task_id = task_creator.create_task()


    def handler_query_task(self, c_print=True):
        """查询任务"""
        self.query_task.query(task_id=self.args.task_id if self.args.task_id else self.task_id)

        if c_print:
            self.query_task.print_query()
        else:
            self.query_task.print_auto()
        
        self.query_task.exit_judgu()

    def handler_save_task(self):
        """保存任务结果"""
        self.handler_query_task(False)
        task_parser = TaskParser(self.config.mime_map)
        task_parser.parse(self.query_task.back_data)
        self.task_data_list = task_parser.task_data
        task_saver = TaskFilterSaver(
            self.task_data_list,
            self.logger,
            AudioSaver(self.logger,self.config.resource.DEFAULT_OUTPUT)
        )
        task_saver.save()
        

    def auto_save(self):
        """自动创建并保存任务"""
        self.handler_create_task()
        auto=TaskAutoSave(
            api_url = self.config.urls.QUERY_TASK_URL,
            config_path = self.config.resource.DEFAULT_OUTPUT,
            mime_map = self.config.mime_map,
            token = self.token_manager,
            logger = self.logger,
            task_id = self.task_id,
            delay = self.args.delay,
            times = self.args.Times
        )
        auto.for_try()  

    def run(self):
        '''执行任务'''
        handler = self.command_handlers.get(self.args.command)
        if handler:
            handler()
        else:
            self.logger.error(f"未知命令: {self.args.command}")


